/*
 * @Description:
 * @version:
 * @Author: m
 * @LastEditors: m
 */
import Vue from "vue";
import Router from "vue-router";
import { getToken } from "@/utils/auth";
import getPageTitle from "@/utils/get-page-title";

const whiteList = ["/login"];

var router = new Router({
	mode: "hash",
	routes: [
		{
			path: "/",
			name: "home",
			component: () => import("@/views/index.vue"),
			meta: { title: "主页面" },
		},
		{
			path: "/order",
			name: "order",
			component: () => import("@/views/order"),
			meta: { title: "订单列表" },
		},
		{
			path: "/order/index",
			name: "orderIndex",
			component: () => import("@/views/order/order.vue"),
			meta: { title: "订单详情" },
		},
		{
			path: "/order/payment",
			name: "orderPayment",
			component: () => import("@/views/order/payment.vue"),
			meta: { title: "去支付" },
		},

		{
			path: "/business",
			name: "business",
			component: () => import("@/views/business"),
			meta: { title: "店铺详情" },
		},
		{
			path: "/business/list",
			name: "businessList",
			component: () => import("@/views/business/list.vue"),
			meta: { title: "店铺列表" },
		},

		{
			path: "/personal",
			name: "personal",
			component: () => import("@/views/personal"),
			meta: { title: "个人中心" },
		},
		{
			path: "/address",
			name: "address",
			component: () => import("@/views/personal/address.vue"),
			meta: { title: "配送地址" },
		},
		{
			path: "/address/add",
			name: "addressAdd",
			component: () => import("@/views/personal/address_add.vue"),
			meta: { title: "新增地址" },
		},

		{
			path: "/login",
			name: "login",
			component: () => import("@/views/login"),
			meta: { title: "用户登录" },
		},
		{
			path: "/register",
			name: "register",
			component: () => import("@/views/register"),
			meta: { title: "用户注册" },
		},
	],
});

router.beforeEach(async (to, from, next) => {
	document.title = getPageTitle();
	console.log(to);

	const hasToken = getToken();

	if (to.path === "/register") {
		next();
	}

	if (hasToken == "undefined" || hasToken == undefined || hasToken == "") {
		if (whiteList.indexOf(to.path) !== -1) {
			next();
		} else if (to.path === "/error") {
			next();
		} else {
			next({ path: "/login" });
		}
	} else {
		next();
	}
});

export default router;

Vue.use(Router);
